package conventer;

import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

public abstract class Converter<B, E> implements IConverter<B, E> {
    @Override
    public B toBean(E entity) {
        return null;
    }

    @Override
    public E toEntity(B bean) {
        return null;
    }

    @Override
    public List<B> toBeans(Collection<E> entities) {
        List<B> modules = new ArrayList<>();
        for (E e : entities) {
            modules.add(toBean(e));
        }
        return modules;
    }

    @Override
    public List<E> toEntities(Collection<B> beans) {
        List<E> entities = new ArrayList<>();
        for (B bean : beans) {
            entities.add(toEntity(bean));
        }
        return entities;
    }


    /**
     * 把对象 o1 转化为 o2
     * 同名属性赋值规则
     * @param o1
     * @param o2
     */
    protected void convert(Object o1, Object o2){
        Class clazz1 = o1.getClass();
        Class clazz2 = o2.getClass();
        Field[] fs2 = clazz2.getDeclaredFields();
        for (Field f2 : fs2){
            try{
                Field f1 = clazz1.getField(f2.getName()); // 获取同名属性
                f2.setAccessible(true);
                f1.setAccessible(true);
                if (f1.getGenericType().equals(f2.getGenericType())){ // 属性类型相同
                    f2.set(o2, f1.get(o1));  // 把o1的属性值赋给o2
                }
            } catch (NoSuchFieldException e) {
            } catch (IllegalAccessException e) {
            }
        }
    }
}
